package mcu.market.net;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.exceptions.IbatisException;
import org.apache.ibatis.session.SqlSession;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;

import mcu.market.ibatis.IBatisFactory;
import mcu.market.ibatis.bean.BeanCompany;
import mcu.market.net.model.getPriceDataModel;
import mcu.market.util.DateUtil;

public class getCompany extends getPriceDataModel{
	@Override
	public String getDataFromURL(Object parameter) {
		String content=null;
		try {
	        ResponseHandler<String> myHandler = new ResponseHandler<String>() {
	        	@Override
	        	public String handleResponse(
	        	        final HttpResponse response) throws IOException {
	        	    return EntityUtils.toString(response.getEntity(), Consts.UTF_8);
	        	}
	        };
	        content= Request.Post("http://mops.twse.com.tw/mops/web/ajax_t51sb01")
					.bodyForm(Form.form().add("TYPEK", String.valueOf(parameter)).add("code", "").add("encodeURIComponent", "1")
					.add("firstin","1").add("step","1").build()).execute().handleResponse(myHandler);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return content;
	}

	@Override
	public List paserData(String content, Object parameter) {
		List<Node> data=null;
		try {
			String f_s="<table style='width:100%;'>";
			String e_s="</table>";
			int first=content.lastIndexOf(f_s);
			content=content.substring(first);
			int end=content.indexOf(e_s);
			content=content.substring(0, end+e_s.length());
			content=content.replaceAll("nowrap", "");
			content=content.replaceAll("<br>", "");
			content=content.replaceAll("&nbsp;", "");
			content=content.replaceAll("&", "");
			Document doc=DocumentHelper.parseText(content);
			data = doc.selectNodes("//tr[@class='odd']|//tr[@class='even']");
		//	List<Node> open = doc.selectNoes("//TD[@class='yfnc_tabledata1']");
		//	List<Node> quote = doc.selectNodes("//TD[@class='yfnc_tabledata1']/SPAN");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data; 
	}

	@Override
	public void insertDataToDB(List list, Object parameter) {
		List<Node> data=list;
		int typek=(int) parameter;
		SqlSession sqlSession=IBatisFactory.getInstance().getSqlSession();
		try {
			for (Node node:data) {
				DateUtil du=new DateUtil();
				BeanCompany bean=new BeanCompany(); 
				bean.setSid(Integer.parseInt(((Node)node.selectNodes("td").get(0)).getText()));
				bean.setName(((Node)node.selectNodes("td").get(1)).getText());
				bean.setChairman(((Node)node.selectNodes("td").get(4)).getText());
				bean.setS_date(du.convertTWDateToADDate(((Node)node.selectNodes("td").get(10)).getText()));
				bean.setIpo_date(du.convertTWDateToADDate(((Node)node.selectNodes("td").get(11)).getText()));
				DecimalFormat df =new DecimalFormat("#,###");
				String num;
				/*fix bug new tab number 2014/1/8
				  num = (df.parse(((Node)node.selectNodes("td").get(12)).getText().trim())).toString();*/
					num = (df.parse(((Node)node.selectNodes("td").get(13)).getText().trim())).toString();
				
				bean.setP_i_c(Long.parseLong(num));
				bean.setType(typek);
				BeanCompany bean_l=new BeanCompany();
				try{
					bean_l =(BeanCompany) sqlSession.selectOne("company.SelectOneCompany",bean);
					if(bean_l==null){
						sqlSession.insert("company.insertCompany",bean);
						sqlSession.commit();  
					}else{
						sqlSession.update("company.updateCompany",bean);
						sqlSession.commit();  
					}
//					sqlSession.close();
//					sqlSession=IBatisFactory.getInstance().getSqlSession();
					
				}catch(IbatisException e){
					e.printStackTrace();
				}
			}
			sqlSession.close();
			System.out.println("公司更新完成");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void execute() {
		String typek[]={"sii","otc"};
		for(int i=0;i<typek.length;i++){
			String content=getDataFromURL(typek[i]);
			List<Node> data=paserData(content,null);
			insertDataToDB(data,i);
		}
		
	}

}
